#coding: utf-8

import urllib2
import urllib
import time

class Stock(object):
    def __init__(self,stockPlatform,*stockCode):
        self.stockCode=stockCode
        self.stockPlatform=stockPlatform
    def getRealData(self,url='http://hq.sinajs.cn/'):
        '''获取股票实时数据
        参数：
        stockPlatform(str):股票交易所
        stockCode(list):股票代码:
        url(str):获取股票数据接口地址
        返回：
        stockData(str) '''
        self.url=url
        newstockCode=[self.stockPlatform + code for code in self.stockCode]
        stockUrl=self.url+"list="+','.join(newstockCode)
        print stockUrl
        stockdataRequest=urllib2.urlopen(stockUrl)
        stockData=stockdataRequest.read()
        stockdataRequest.close()
        return stockData
    def getHistoryData(self):
        pass
    def parseRealData(self,RealData,codenum):
        '''解析实时股票数据
        参数：
        RealData(str):查询接口返回的股票原始数据
        dataNum(int):查询股票的数目
        返回:stockRealDatas (dict)
        '''
        stockRealDatas={}
        stockRealValues=[]
        # tempfile='temp.txt'
        # fp=open('temp.txt',mode='r')
        # RealData=fp.read()
        # fp.close()
        stockDatalist=RealData.split(';',codenum-1)
        print stockDatalist
        for stockData in stockDatalist:
            stockRealValues.append(stockData.strip().split('=',1)[1].strip(';').strip('"'))
        zipstockdatas=zip(self.stockCode,stockRealValues)
        for code,value in zipstockdatas:
            stockRealDatas[code]=value
        return stockRealDatas
    def parseHistoryData(self):
        pass
    def displayRealData(self,realDatas):
        '''将数据以图标的形式展现
        参数：
        realDatas:实时数据
        返回：'''
        #文件方式存储实时数据
        lt = time.localtime()
        TIMEFORMAT = '%Y-%m-%d'
        datetime=time.strftime(TIMEFORMAT, lt)
        datafile=datetime + 'stockData.txt'
        needsaveData = {}
        fp=open(datafile,mode='a')
        for code,value in realDatas.items():
            valueList = value.split(',')
            #保存开盘价、日期时间
            savedata = [valueList[0], valueList[3], valueList[30], valueList[31]]
            needsaveData[code] = savedata
            writedata = code + ',' + ','.join(savedata) + '\n'
            fp.write(writedata)
        fp.close()
        #读取全部数据
        rp=open(datafile,mode='r')
        #allStockDatas=rp.read()
        #print "allStockDatas is:",allStockDatas
        #提取并格式化数据
        for data in rp.readlines():
            print data
        rp.close()
        #展现数据

    def displayHistoryData(self):
        pass

if __name__ == '__main__':
    stockcode=['601006','600198']
    stock = Stock('sh',*stockcode)
    stockRealRawDatas=stock.getRealData()
    stockRealDatas=stock.parseRealData(stockRealRawDatas,len(stockcode))
    print "stockRealDatas is:", stockRealDatas
    stock.displayRealData(stockRealDatas)

    #print stockRealDatas['601006'].decode('gbk')


